package com.acquisition.task.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 反射工具类
 *
 * @author wuqiwei
 * @date 2021/01/18
 */
public class ReflectionUtils {

	public static Method getDeclaredMethod(Object object, String methodName, Class<?>... parameterTypes) {
		Method method = null;
		for (Class<?> clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
			try {
				if (clazz != null) {
					method = clazz.getDeclaredMethod(methodName, parameterTypes);
				}
				return method;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static Object invokeMethod(Object object, String methodName, Class<?>[] parameterTypes, Object[] parameters) {
		Method method = getDeclaredMethod(object, methodName, parameterTypes);
		if (method != null) {
			method.setAccessible(true);
			try {
				return method.invoke(object, parameters);
			} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static Field getDeclaredField(Object object, String fieldName) {
		Field field = null;
		for (Class<?> clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
			try {
				if (clazz != null) {
					field = clazz.getDeclaredField(fieldName);
				}
				return field;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static void setFieldValue(Object object, String fieldName, Object value) {
		Field field = getDeclaredField(object, fieldName);
		if (field != null) {
			field.setAccessible(true);
			try {
				field.set(object, value);
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}

	public static Object getFieldValue(Object object, String fieldName) {
		Field field = getDeclaredField(object, fieldName);
		if (field != null) {
			field.setAccessible(true);
			try {
				return field.get(object);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
